package com.augurit.wf.jbpmex.cmd;

import java.util.Calendar;
import java.util.Date;

import org.jbpm.api.cmd.Environment;
import org.jbpm.pvm.internal.cal.Duration;
import org.jbpm.pvm.internal.cmd.AbstractCommand;

/**
 * 计算两个日期之间的工作日
 * @author Administrator
 *
 */
public class CalculateBussinessDaysCmd extends AbstractCommand<Integer>{
	
	private static final long serialVersionUID = 1L;
	
	private Date startDate;
	private Date endDate;
	
	public CalculateBussinessDaysCmd(Date startDate,Date endDate){
		this.startDate = startDate;
		this.endDate = endDate;
	}
	
	/**
	 * 获取开始日期与结束日期之间的工作日天数
	 */
	public Integer execute(Environment environment) throws Exception {
		Integer num = -1;
		
		//开始日期要小于结束日期
		if(startDate.before(endDate)){
			for(int i=0;i<367;i++){
				String durationExpression = i + " business day";
				Date destDate = Duration.calculateDueDate(durationExpression);
				if(isSameDay(destDate))
					return i;
			}
		}
		return num;
	}
	
	/**
	 * 如果两个日期的年月日相等,就认为两个日期相同
	 * @param destDate
	 * @return
	 */
	public boolean isSameDay(Date destDate){
		if(destDate != null){
			Calendar cal = Calendar.getInstance();
			cal.setTime(endDate);
			Calendar destCal = Calendar.getInstance();
			destCal.setTime(destDate);
			
			//如果两个日期的年月日相等,就返回ture
			if(cal.get(Calendar.YEAR) == destCal.get(Calendar.YEAR)
					&& cal.get(Calendar.MONTH) == destCal.get(Calendar.MONTH)
					 && cal.get(Calendar.DATE) == destCal.get(Calendar.DATE))
				return true;
		}
		return false;
	}
}
